<template>
  <div class="api-test-container">
    <a-card title="API 测试页面" :bordered="false">
      <p>
        该页面用于测试系统 API 接口。展示了所有可用接口及其参数，您可以点击"测试"按钮发送请求并查看响应结果。
        如果接口调用失败，系统会显示错误信息并尝试提供 Mock 数据以供参考。
      </p>
      
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="admin" tab="后台管理">
          <api-list-table :api-list="apiList.admin" @test-api="handleApiTest" />
        </a-tab-pane>
        <a-tab-pane key="user" tab="用户管理">
          <api-list-table :api-list="apiList.user" @test-api="handleApiTest" />
        </a-tab-pane>
        <a-tab-pane key="quota" tab="配额管理">
          <api-list-table :api-list="apiList.quota" @test-api="handleApiTest" />
        </a-tab-pane>
        <a-tab-pane key="parking" tab="车位管理">
          <api-list-table :api-list="apiList.parking" @test-api="handleApiTest" />
        </a-tab-pane>
        <a-tab-pane key="special" tab="特殊日期">
          <api-list-table :api-list="apiList.special" @test-api="handleApiTest" />
        </a-tab-pane>
      </a-tabs>
      
      <a-divider v-if="response || error || mockResponse">响应结果</a-divider>
      
      <div v-if="error" class="error-container">
        <a-collapse :default-active-key="['1']">
          <a-collapse-panel key="1" header="错误信息">
            <div class="error-info">
              <a-typography-text type="danger">错误信息: {{ error.message }}</a-typography-text>
              <br v-if="error.status" />
              <a-typography-text v-if="error.status" type="danger">状态码: {{ error.status }}</a-typography-text>
              <div v-if="error.data">
                <a-typography-text type="danger">错误详情:</a-typography-text>
                <pre>{{ JSON.stringify(error.data, null, 2) }}</pre>
              </div>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </div>
      
      <div v-if="mockResponse" class="mock-container">
        <a-collapse :default-active-key="error ? [] : ['1']">
          <a-collapse-panel key="1" header="Mock 数据">
            <pre>{{ JSON.stringify(mockResponse, null, 2) }}</pre>
          </a-collapse-panel>
        </a-collapse>
      </div>
      
      <div v-if="response" class="response-container">
        <a-collapse :default-active-key="['1']">
          <a-collapse-panel key="1" header="接口响应">
            <pre>{{ JSON.stringify(response, null, 2) }}</pre>
          </a-collapse-panel>
        </a-collapse>
      </div>
    </a-card>
  </div>
</template>

<script>
import { defineComponent, ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import ApiListTable from '../components/ApiTest/ApiListTable.vue';
import { get, post } from '../https';
import mockData from '../https/mockData';
import * as apiServices from '../api/index';

export default defineComponent({
  name: 'ApiTest',
  components: {
    ApiListTable
  },
  setup() {
    const activeTab = ref('admin');
    const loading = ref(false);
    const response = ref(null);
    const error = ref(null);
    const mockResponse = ref(null);
    
    // 根据 api/index.js 中的方法创建 API 列表
    const apiList = {
      // 后台管理相关接口
      admin: [
        {
          name: '添加后台用户',
          method: 'get',
          url: '/api/manager/add',
          description: '添加新的后台管理员账号',
          params: [
            { name: 'username', type: 'string', description: '用户名', required: true },
            { name: 'password', type: 'string', description: '密码', required: true }
          ]
        },
        {
          name: '后台用户登录',
          method: 'get',
          url: '/api/login',
          description: '后台用户登录接口',
          params: [
            { name: 'username', type: 'string', description: '用户名', required: true },
            { name: 'password', type: 'string', description: '密码', required: true }
          ]
        },
        {
          name: '后台用户退出登录',
          method: 'get',
          url: '/api/logout',
          description: '后台用户退出登录接口'
        }
      ],
      
      // 用户管理相关接口
      user: [
        {
          name: '获取用户列表',
          method: 'get',
          url: '/api/admin/users/list',
          description: '获取用户列表，包含季度配额信息',
          params: [
            { name: 'search', type: 'string', description: '搜索关键词 (用户名、手机号、车牌号)' },
            { name: 'per_page', type: 'number', description: '每页显示记录数', defaultValue: 15 },
            { name: 'page', type: 'number', description: '页码', defaultValue: 1 }
          ]
        },
        {
          name: '添加用户',
          method: 'get',
          url: '/api/admin/users/add',
          description: '添加新用户',
          params: [
            { name: 'name', type: 'string', description: '姓名', required: true },
            { name: 'phone', type: 'string', description: '手机号', required: true },
            { name: 'license_plate', type: 'string', description: '车牌号', required: true },
            { name: 'is_new_energy', type: 'select', description: '是否新能源车', required: true,
              options: [
                { label: '是', value: true },
                { label: '否', value: false }
              ]
            }
          ]
        },
        {
          name: '获取用户详情',
          method: 'get',
          url: '/api/admin/users/show/:id',
          description: '根据ID获取用户详情',
          pathParams: [
            { name: 'id', type: 'number', description: '用户ID', required: true }
          ]
        },
        {
          name: '修改用户信息',
          method: 'get',
          url: '/api/admin/users/update/:id',
          description: '修改用户基本信息',
          pathParams: [
            { name: 'id', type: 'number', description: '用户ID', required: true }
          ],
          params: [
            { name: 'name', type: 'string', description: '姓名' },
            { name: 'phone', type: 'string', description: '手机号' },
            { name: 'license_plate', type: 'string', description: '车牌号' },
            { name: 'is_new_energy', type: 'select', description: '是否新能源车',
              options: [
                { label: '是', value: true },
                { label: '否', value: false }
              ]
            },
            { name: 'is_active', type: 'select', description: '状态',
              options: [
                { label: '启用', value: true },
                { label: '禁用', value: false }
              ]
            }
          ]
        }
      ],
      
      // 季度配额管理接口
      quota: [
        {
          name: '批量修改用户配额',
          method: 'get',
          url: '/api/admin/users/batch-update-quota',
          description: '批量修改用户季度配额',
          params: [
            { name: 'quarter', type: 'select', description: '季度', required: true,
              options: [
                { label: '当前季度', value: 'current' },
                { label: '下季度', value: 'next' }
              ]
            },
            { name: 'quota', type: 'number', description: '设置的配额值', required: true }
          ]
        },
        {
          name: '获取季度配额统计',
          method: 'get',
          url: '/api/admin/users/get-quota',
          description: '获取季度配额统计信息'
        }
      ],
      
      // 车位管理相关接口
      parking: [
        {
          name: '添加车位',
          method: 'get',
          url: '/api/admin/parking-space/add',
          description: '添加新的停车位',
          params: [
            { name: 'space_number', type: 'string', description: '车位编号，唯一标识', required: true },
            { name: 'status', type: 'select', description: '状态', required: true,
              options: [
                { label: '可用', value: 'active' },
                { label: '不可用', value: 'inactive' }
              ]
            },
            { name: 'notes', type: 'textarea', description: '备注信息' }
          ]
        },
        {
          name: '获取车位列表',
          method: 'get',
          url: '/api/admin/parking-space/list',
          description: '获取停车位列表',
          params: [
            { name: 'space_number', type: 'string', description: '车位编号筛选' },
            { name: 'per_page', type: 'number', description: '每页显示记录数', defaultValue: 15 },
            { name: 'page', type: 'number', description: '页码', defaultValue: 1 }
          ]
        },
        {
          name: '编辑车位',
          method: 'get',
          url: '/api/admin/parking-space/update/:id',
          description: '编辑停车位信息',
          pathParams: [
            { name: 'id', type: 'number', description: '车位ID', required: true }
          ],
          params: [
            { name: 'space_number', type: 'string', description: '车位编号，唯一标识', required: true },
            { name: 'status', type: 'select', description: '状态', required: true,
              options: [
                { label: '可用', value: 'active' },
                { label: '不可用', value: 'inactive' }
              ]
            },
            { name: 'notes', type: 'textarea', description: '备注信息' }
          ]
        }
      ],
      
      // 特殊日期管理接口
      special: [
        {
          name: '添加特殊日期',
          method: 'get',
          url: '/api/admin/special-dates/add',
          description: '添加额度消耗规则 (管理假期)',
          params: [
            { name: 'date', type: 'string', description: '日期 (YYYY-MM-DD)', required: true },
            { name: 'name', type: 'string', description: '备注', required: true },
            { name: 'booking_cost', type: 'string', description: '消耗额度', required: true }
          ]
        },
        {
          name: '删除特殊日期',
          method: 'get',
          url: '/api/admin/special-dates/del/:id',
          description: '删除额度消耗规则 (管理假期)',
          pathParams: [
            { name: 'id', type: 'number', description: '特殊日期ID', required: true }
          ]
        }
      ]
    };
    
    const handleApiTest = async (api, params = {}) => {
      loading.value = true;
      response.value = null;
      error.value = null;
      mockResponse.value = null;
      
      // 处理路径参数
      let url = api.url;
      if (api.pathParams && api.pathParams.length > 0) {
        api.pathParams.forEach(param => {
          if (params[param.name]) {
            url = url.replace(`:${param.name}`, params[param.name]);
          }
        });
      }
      
      // 查找 Mock 数据
      const mockKey = `${api.method}:${api.url.replace(/^\/api\//, '')}`;
      const mockDataForApi = mockData[mockKey];
      if (mockDataForApi) {
        mockResponse.value = mockDataForApi;
      }
      
      try {
        let result;
        if (api.method === 'get') {
          // 移除路径参数，只保留查询参数
          const queryParams = { ...params };
          if (api.pathParams) {
            api.pathParams.forEach(param => {
              delete queryParams[param.name];
            });
          }
          result = await get(url, queryParams);
        } else if (api.method === 'post') {
          // 移除路径参数，只保留请求体参数
          const bodyParams = { ...params };
          if (api.pathParams) {
            api.pathParams.forEach(param => {
              delete bodyParams[param.name];
            });
          }
          result = await post(url, bodyParams);
        }
        
        response.value = result;
        message.success('请求成功');
      } catch (err) {
        error.value = {
          message: err.message,
          status: err.response?.status,
          data: err.response?.data
        };
        message.error('请求失败');
      } finally {
        loading.value = false;
      }
    };
    
    return {
      activeTab,
      loading,
      response,
      error,
      mockResponse,
      apiList,
      handleApiTest
    };
  }
});
</script>

<style scoped>
.api-test-container {
  padding: 20px;
}

.error-container {
  margin-bottom: 16px;
}

.error-info {
  padding: 12px;
  background-color: #fff2f0;
  border-radius: 4px;
}

.error-info pre {
  margin-top: 8px;
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  overflow: auto;
}

.mock-container {
  margin-bottom: 16px;
}

.mock-container pre, 
.response-container pre {
  margin: 0;
  padding: 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: auto;
  max-height: 400px;
}

.response-container pre {
  background-color: #f6ffed;
}
</style> 